package com.struts.filter;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.struts.config.ActionConfig;
import com.struts.config.ConfigurationManager;
import com.struts.context.ActionContext;
import com.struts.invocation.InvocationWrap;

public class StrutsPrepareAndExecuterFilter implements Filter {

	// 存放拦截器中每个拦截器全限定类名
	private List<String> interceptors;
	// 请求后缀
	private String extension;
	// 所有action配置信息
	private Map<String, ActionConfig> actionConfigs;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		interceptors = ConfigurationManager.getInterceptors();
		extension = ConfigurationManager.getConstant("struts.action.extension");
		actionConfigs = ConfigurationManager.getActions();
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String reqPath = req.getServletPath();
		if (!reqPath.endsWith(extension)) {
			chain.doFilter(request, response);
		} else {
			reqPath = reqPath.substring(1);
			reqPath = reqPath.replace("." + extension, "");
			ActionConfig actionConfig = actionConfigs.get(reqPath);
			if (actionConfig == null) {
				throw new RuntimeException("未找到" + reqPath + "的配置信息");
			}
			// 创建ActionInvocation，完成对拦截器链和action的调用
			try {
				InvocationWrap invocation = new InvocationWrap(interceptors, actionConfig, req, resp);
				String result = invocation.invoke(invocation);
				// 根据结果串查找配置信息中的对应路径
				String dispatcherPath = actionConfig.getResults().get(result);
				if (dispatcherPath == null || "".equals(dispatcherPath.trim())) {
					throw new RuntimeException("未找到" + result + "对应的路径");
				}
				// 请求转发配置的路径
				req.getRequestDispatcher(dispatcherPath).forward(request, response);
				// 释放资源
				ActionContext.actionContext.remove();
			} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException
					| InvocationTargetException | NoSuchMethodException | SecurityException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void destroy() {

	}

}
